﻿// fix overflow dragdrop bug
var SubsDraggable = Class.create();
SubsDraggable.prototype = Object.extend({}, Draggable.prototype);
Object.extend(SubsDraggable.prototype, {
	draw: function(point) {
    var pos = Position.cumulativeOffset(this.element);
	var _scrollTop = this.options._scroll ? this.options._scroll.scrollTop : 0;
    if(this.options.ghosting) {
      var r   = Position.realOffset(this.element);
      pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
    }

    var d = this.currentDelta();
    pos[0] -= d[0]; pos[1] -= d[1];

    if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
    }

    var p = [0,1].map(function(i){
      return (point[i]-pos[i]-this.offset[i])
    }.bind(this));

    if(this.options.snap) {
      if(Object.isFunction(this.options.snap)) {
        p = this.options.snap(p[0],p[1],this);
      } else {
      if(Object.isArray(this.options.snap)) {
        p = p.map( function(v, i) {
          return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
      } else {
        p = p.map( function(v) {
          return (v/this.options.snap).round()*this.options.snap }.bind(this));
      }
    }}

    var style = this.element.style;
    if((!this.options.constraint) || (this.options.constraint=='horizontal'))
      style.left = p[0] + "px";
    if((!this.options.constraint) || (this.options.constraint=='vertical'))
      style.top  = p[1] - _scrollTop + "px";

    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  }
});

var MailAddress = Class.create();
MailAddress.prototype = {
	/**
	 * initialize函数将会在初始化地址本的时候构建地址本相关信息的缓存：地址本联系人，组列表，最近联系人列表，黑名单，白名单；联系人的DOM缓存 。。。
	 */
	initialize : function() {
		/*
		// 当前组对象
		this.currentGroup = {};
		// 所有联系人组对象
		this.currentAllGroup = {};
		// 当前联系人
		this.currentContact = {};
		// 地址薄界面首页HTML内容（如果用户没有动态改变地址薄内容，返回地址薄首页面将直接调用这里的内容显示）
		this.addressHTML = "";
		// 地址薄左下 联系人列表HTML
		this.contactListsHTML = "";
		// this.initData();
		this.searchkey_all = null;
		*/
		
		// 联系人地址本达到上限500条的提示信息，最近联系人上限为20条
		this.addrLimit = 500;
		this.rectLimit = 20;
		this.limitInfo = '您的地址簿联系人已经达到保存上限'+ this.addrLimit +'条。您可以清除一些长期不用的联系人。';
		
		// 邮件main的DOM元素
		this.sohuMailMain = $('sohuMailMain');
		// 地址簿区域的DOM元素
		this.ADDR = $('addressGroupList');
		// 当前显示的组ID（默认是所有组）
		this.currentGroupId = -2;
		// 是否是通过历史记录进来的
		this.rsh = false;
		// 组列表的坐标点
		this.drops = [];
		this.dragflag = false;
		// 当前联系人列表的拖拽事件
		this.dragEventList = [];
		// 组中成员列表
		this.groupItemList = [];
		// 存取地址本中可获取到积分的缓存
		this.scoreHash = {};
		// 缓存contact list DOM的列表
		this.mailAddrListDOM = [];
		// 缓存最近联系人但不在用户联系人列表里面的DOM
		this.mailRecentListDOM = [];
		this.AddrList = document.createElement('div');
		// 当键盘按住ctrl，在组中进行拖拽的时候，就是对组中成员的复制
		this.ctrl_down = false;
		Event.observe(document, 'keydown', function(event) {
			if(event.ctrlKey) {
				this.ctrl_down = true;
			}
		}.bind(this));
		Event.observe(document, 'keyup', function(event) {
			if(!event.ctrlKey) {
				this.ctrl_down = false;
			}
		}.bind(this));
		this.initCache();
        this.is_tourial = false;
		// this.addressCache = {};
	},
	
	// 初始化事件
	initEvent: function() {
		var self = this;
		var _tmp_dl = [
			{name: 's_addr_write', exec: function() {
				self.contactsWriteMail();
			}},
			{name: 's_addr_new', exec: function() {
				self.createContact();
			}},
			{name: 's_addr_add', exec: function(EL, event) {
				var menulist = [];
				contactCates.each(function(item) {
					if(item.id == 0 || item.id == -1) return;
					var _it = {
						text: item.name,
						onclick: function() {
							if(!self.addsGroup(item.id)) {
								return false;
							}
							self.initGroup(item.id);
							self.groupsNum();
							return false;
						}
					};
					menulist.push(_it);
				});
				// var e = EL.nodeName.toLowerCase() == 'a' ? EL : EL.parentNode.nodeName.toLowerCase() == 'a' ? EL.parentNode : EL.parentNode.parentNode.nodeName.toLowerCase() == 'a' ? EL.parentNode.parentNode : null;
				if (EL) {
					menu.showMenu(EL, DOM.sohuMailMain, menulist, 'menu', true, null, event);
					// menu.showMenu(EL, DOM.sohuMailMain, menulist, 'menu', true, null, event);
				}
			}},
			{name: 's_addr_edit', exec: function() {
				self.getC(self.getChecked()[0]);
			}},
			{name: 's_addr_del', exec: function() {
				self.deleteContact();
			}},
			{name: 's_addr_create_group', exec: function() {
				self.createGroup();
			}},
			{name: 's_addr_import', exec: function() {
				self.importAddress();
			}},
			{name: 's_addr_group', exec: function(EL, event) {
				// var e = Element.hasClassName(EL, 's_addr_group') ? EL : Element.hasClassName(EL.parentNode, 's_addr_group') ? EL.parentNode : Element.hasClassName(EL.parentNode.parentNode, 's_addr_group') ? EL.parentNode.parentNode : null;
				var gid = EL.gid ? EL.gid : EL.getAttribute('gid');
				self.initGroup(gid);
			}},
			{name: 's_addr_setall', exec: function(EL, event) {
				self.setAll(EL.checked);
			}},
			{name: 's_addr_edit_group', exec: function(EL, event) {
				var gid = EL.gid ? EL.gid : EL.getAttribute('gid');
				self.createGroup(true, gid);
			}},
			{name: 's_addr_send_group', exec: function(EL, event) {
				var gname = EL.gname ? EL.gname : EL.getAttribute('gname');
				self.groupWriteMail(gname);
			}},
			{name: 's_addr_del_group', exec: function(EL, event) {
				var gid = EL.gid ? EL.gid : EL.getAttribute('gid');
				self.deleteGroup(gid);
			}},
			{name: 's_addr_main_page', exec: function() {
				self.init();
			}},
			{name: 's_addr_cancel_import', exec: function() {
				self.cancelImport();
			}},
			{name: 's_addr_import_addr', exec: function() {
				self.importAddr();
			}},
			{name: 's_addr_import_other', exec: function(EL, event) {
				self.importOtherAddress(EL);
			}},
			{name: 's_addr_send_mail', exec: function(EL, event) {
				self.sendMail();
			}},
			{name: 's_addr_group_add', exec: function() {
				self._add();
			}},
			{name: 's_addr_group_del', exec: function() {
				self._delete();
			}},
			{name: 's_addr_create_g', exec: function() {
				self.createG();
			}},
			{name: 's_addr_create_c', exec: function() {
				self.createC();
			}},
			{name: 's_addr_show_info', exec: function(EL, event) {
				self.switchInfoPanel(EL, 'otherInfoDiv');
			}},
			{name: 's_addr_show_dinfo', exec: function(EL, event) {
				self.switchInfoPanel(EL, 'detailInfoDiv');
			}}
		];
		
		/*
		Event.observe(DOM.addressGroupList, 'click', function(event) {
			var EL = $(event.target);
			try {
				_tmp_dl.each(function(item){
					var e = Element.getParentNodeByClassName(EL, item.name);
					if (e) {
						item.exec(e, event);
					}
					if(e && e.nodeName.toLowerCase() == 'a') {
						Event.stop(event);
					}
					return false;
				});
			} catch(e) {}
			return false;
		});
		*/
		var _gpcn = Element.getParentNodeByClassName, _gpatr = Element.getParentNodeByAttribute;
		DOM.addressGroupList.observe('click', function(event) {
			var el = event.target;
			_tmp_dl.each(function(item) {
				var e = _gpcn(el, item.name);
				if(e) {
					item.exec(e, event);
				}
				if(e && e.nodeName.toLowerCase() == 'a') {
					Event.stop(event);
				}
				return false;
			});
		}).observe('mouseover', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-hover');
		}).observe('mouseout', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-hover');
		}).observe('mousedown', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-press');
		}.bind(this)).observe('mouseup', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-press');
		});
		
		
	},
	
	initCache: function(is_request) {
		this.addressHash = {contact:{email:{},id:{},email2id:{}}, group:{}};
		if(is_request || !ADDRESSES.isJSON()) {
			try {
				this.mailAddrListDOM = [];
				this.mailRecentListDOM = [];
			} catch(e) {}
			mail_address({}, this.initCacheCallback.bind(this, true));
		} else {
			try {
				this.initCacheCallback(false, ADDRESSES.evalJSON());
			} catch(e) {}
		}
	},
	
	initCacheCallback: function(rf, ret) {
		this.addressCache = ret;
		contactLists = this.addressCache.contact ? this.addressCache.contact.slice(0, this.addrLimit) : [];
		contactCates = this.addressCache.group ? this.addressCache.group : [];
		recentLists = this.addressCache.recent ? this.addressCache.recent.slice(0, this.rectLimit) : [];
		whiteLists = this.addressCache.white ? this.addressCache.white : [];
		blackLists = this.addressCache.black ? this.addressCache.black : [];
		whiteOnly = this.addressCache.whiteonly ? this.addressCache.whiteonly : 0;
		// 所有联系人组，最近联系人组通过前端组织他们的数据结构，id分别定为0，-1
		var all_group = {pinyin: 'suo', id: 0, name: '所有联系人', contactid: ''}, alg = [];
		contactLists.each(function(item) {
			alg.push(item.id);
			try {
				this.addressHash.contact.email[item.email] = item.nickname;
				this.addressHash.contact.id[item.id] = item.email;
				this.addressHash.contact.email2id[item.email] = item.id;
			} catch(e) {}
			try {
				var adiv = this.createListItem(item);
				this.mailAddrListDOM.push(adiv);
			} catch(e) {}
		}.bind(this));
		all_group.contactid = alg.join(',');
		contactCates.unshift(all_group);
		
		if (rf) {
			try {
				this.initCacheOtherCallback(ret);
			} catch (e) {}
			return false;
		}
		
		try {
			var self = this, _o_ifr = $('otherAddrData'), _index = 0,
			_load_other_addr_data = function() {
				var _j = (function() {
					try {
						return (!_o_ifr || !_otherAddrData.loaded);
					} catch(e) {
						return true;
					}
				})();
				if(_j && _index < 5) {
					setTimeout(arguments.callee, 1000);
					_index ++;
					return false;
				}
				_otherAddrDataLoaded = _o_ifr.contentWindow._otherAddrDataLoaded;
				if(!_otherAddrDataLoaded) {
					loadScript(_otherAddrData.url, function() {
						try {
							if(!_otherAddrDataLoaded) return;
						} catch(e) {
							return;
						}
						self.initCacheOtherCallback(_otherAddrDataLoaded.evalJSON());
					});
					_o_ifr.parentNode.removeChild(_o_ifr);
					_o_ifr = null;
				} else {
					self.initCacheOtherCallback(_otherAddrDataLoaded.evalJSON());
				}
			};
			_load_other_addr_data();
		} catch(e) {}
	},
	initCacheOtherCallback: function(ret) {
		if(typeof ret != 'object') return false;
		
		this.addressCache = Object.extend(this.addressCache, ret);
		contactCates = contactCates.concat(this.addressCache.group ? this.addressCache.group : []);
		recentLists = this.addressCache.recent ? this.addressCache.recent.slice(0, this.rectLimit) : [];
		whiteLists = this.addressCache.white ? this.addressCache.white : [];
		blackLists = this.addressCache.black ? this.addressCache.black : [];
		whiteOnly = this.addressCache.whiteonly ? this.addressCache.whiteonly : 0;
		
		var rec_group = {pinyin: 'zui', id: -1, name: '最近联系人', contactid: ''}, rec = [];
		recentLists.each(function(item) {
			rec.push(item.id);
			try {
				var adiv = this.createListItem(item);
				this.mailRecentListDOM.push(adiv);
			} catch(e) {}
		}.bind(this));
		rec_group.contactid = rec.join(',');
		contactCates.unshift(rec_group);
			
		contactCates.each(function(item) {
			var tmpF = function(cid) {
				if(cid == '') return '';
				var _c = cid.split(',');
				var _t = [];
				_c.each(function(_item) {
					var em = this.addressHash.contact.id[_item];
					if(em) _t.push(em);
				}.bind(this));
				return _t.join(',');
				tmpF = null;
			}.bind(this);
			this.addressHash.group[item.name] = tmpF(item.contactid);
		}.bind(this));
	},
	
	createListItem: function(item) {
		var adiv = document.createElement('div');
				adiv.setAttribute('id', 'addr_list_'+item.id);
				adiv.setAttribute('contact_id', item.id);
				with(adiv.style) {
					width = '100%';
					clear = 'both';
					height = '30px';
					position = 'relative';
				};
				var data = {};
				data['id'] = item.id;
				data['nickname'] = item.nickname;
				data['email'] = item.email;
				data['pinyin'] = item.pinyin;
				data['inContact'] = item.inContact;
				var cont_item = new Template(addr_contact_item).evaluate(data);
				adiv.innerHTML = '<div class="contact_item">'+ cont_item +'</div>';
				var drag_div = document.createElement('div');
				drag_div.className = 'contact_item_reflex';
				drag_div.innerHTML = cont_item;
				
				var adiv_d = adiv.firstChild;
				adiv.appendChild(drag_div);
				var self = this;
				var _d = adiv.firstChild.getElementsByTagName('div')[1];
				var _dw = adiv.firstChild.lastChild;
				var _dd = drag_div.getElementsByTagName('div')[1];
				var d_1 = _d.firstChild;
				var d_2 = _d.lastChild;
				var d_3 = _dd.firstChild;
				var _blur = function(event) {
					d_2.style.display = 'none';
					var _v = d_2.firstChild.value;
					if(this._check_length(_v) > 20) {
						_dialog.alert({info: '联系人昵称太长！请限制在10个汉字或20个英文字母以内！'});
						d_1.style.display = '';
						return;
					}
					with(d_1) {
						style.display = '';
						firstChild.innerHTML = _v;
					};
					d_3.firstChild.innerHTML = _v;
					if(item.nickname == _v) return;
					item.nickname = _v;
					var params = {
						id: item.id,
						nickname: item.nickname
					};
					// var el = event.srcElement ? event.srcElement : event.target;
					edit_contact(params, function(ret) {
						if(ret.status) {
							var _flag = false;
							contactLists.each(function(item) {
								if(item.id == ret.msg.id) _flag = true;
							});
							if(self.currentGroupId == -1) {
								self.setAddrItemNick(item);
							} else {
								self.setRecentItemNick(item);
							}
							if (!_flag) {
								var _a = d_1.firstChild.nextSibling.firstChild;
								var pars = {
									nickname: item.nickname,
									email: item.email
								};
								var confunc_add_con = function() {
									add_contact(pars, function(ret){
										contactLists.push(ret.msg);
										var adiv = self.createListItem(ret.msg);
										self.mailAddrListDOM.push(adiv);
										_a.innerHTML = '[编 辑]';
										_a.onclick = function() {
											mailAddressClass.getC(ret.msg.id);
											return false;
										};
										$('addr_group_0').getElementsByTagName('strong')[1].innerHTML = '(' + contactLists.length + ')';
										$('messageDiv').show();
										var __t = setTimeout(function(){
											clearTimeout(__t);
											__t = null;
											$('messageDiv').hide();
										}, 3000);
									});
								}
								var _new_blist = self.delItemByBlack(item.email);
								if(blackLists.length != _new_blist.length) {
									_dialog.confirm({info: '该地址在黑名单中，添加到地址簿会将其从黑名单中删除，是否继续？', click: function() {
										blackLists = _new_blist;
										confunc_add_con();
									}});
									return false;
								}
								confunc_add_con();
								_a = null;
								return false;
							}
						}
					});
				}.bind(this);
				Event.observe(adiv_d, 'mouseover', this.contact_over.bind(this, adiv.firstChild));
				Event.observe(adiv_d, 'mouseout', this.contact_out.bind(this, adiv.firstChild));
				Event.observe(_dw, 'click', function() {
					mailAddressClass.groupWriteMail(item.email);
					return false;
				});
				Event.observe(d_1.firstChild, 'click', function(event) {
					d_1.style.display = 'none';
					with(d_2) {
						style.display = 'block';
						firstChild.value = d_1.firstChild.innerHTML;
						firstChild.focus();
					};
					try {
						jsoplog.ucCapture('addrnameedit');
					} catch(e) {}
					Event.stop(event);
					return false;
				});
				var __a = d_1.firstChild.nextSibling.firstChild;
				var _bind_clk_event = function() {
					mailAddressClass.getC(item.id);
					return false;
				};
				Event.observe(__a, 'click', _bind_clk_event);
				// var _ed = null;
				Event.observe(_d.firstChild, 'mouseover', function(event) {
					var _a = __a;
					_a.style.visibility = 'visible';
					if (self.currentGroupId != -1) {
						_a = null;
						return;
					}
					var ___flag = false;
					contactLists.each(function(__item) {
						if(__item.email == item.email) ___flag = true;
					});
					if(!___flag) {
						if (_a.innerHTML.include('添加为联系人')) {
							_a = null;
							return;
						}
						_a.innerHTML = '[添加为联系人]';
						try {
							Event.stopObserving(_a, 'click');
						} catch(e) {}
						Event.observe(_a, 'click', function(event) {
							var pars = {
								nickname: item.nickname,
								email: item.email
							};
							var confunc_add_con = function() {
								add_contact(pars, function(ret) {
									contactLists.push(ret.msg);
									var adiv = self.createListItem(ret.msg);
									self.mailAddrListDOM.push(adiv);
									_a.innerHTML = '[编 辑]';
									var _clk_event = function() {
										mailAddressClass.getC(ret.msg.id);
										return false;
									};
									try {
										Event.stopObserving(_a, 'click');
									} catch(e) {}
									Event.observe(_a, 'click', _clk_event);
									_clk_event = null;
									$('addr_group_0').getElementsByTagName('strong')[1].innerHTML = '(' + contactLists.length + ')';
									var __msg = $('messageDiv');
									__msg.show();
									var __t = setTimeout(function() {
										clearTimeout(__t);
										__t = null;
										try {
											__msg.hide();
										} catch(e) {}
										__msg = null;
									}, 3000);
								});
							};
							var _new_blist = self.delItemByBlack(item.email);
							if(blackLists.length != _new_blist.length) {
								_dialog.confirm({info: '该地址在黑名单中，添加到地址簿会将其从黑名单中删除，是否继续？', click: function() {
									blackLists = _new_blist;
									confunc_add_con();
								}});
								return false;
							}
							confunc_add_con();
							return false;
						});
					} else {
						if (_a.innerHTML.include('编 辑')) {
							_a = null;
							return;
						}
						_a.innerHTML = '[编 辑]';
						try {
							Event.stopObserving(_a, 'click');
						} catch(e) {}
						Event.observe(_a, 'click', _bind_clk_event);
					}
					// _a = null;
					return false;
				});
				Event.observe(_d.firstChild, 'mouseout', function(event) {
					var _a = d_1.firstChild.nextSibling.firstChild;
					_a.style.visibility = 'hidden';
					_a = null;
					return false;
				});
				Event.observe(d_2.firstChild, 'blur', function(event) {
					_blur(event);
					return false;
				});
				Event.observe(d_2.firstChild, 'keydown', function(event) {
					if(event.keyCode == 13) _blur(event);
					return false;
				});
				// fix other browser bug
				if (!Prototype.Browser.IE) {
					Event.observe(d_2.firstChild, 'click', function(event) {
						Event.stop(event);
						return false;
					});
					Event.observe(adiv, 'click', function(event) {
						if (d_2.style.display == 'none') 
							return;
						_blur(event);
						return false;
					});
				}
				_bind_clk_event = null;
		return adiv;
	},
	
	/*------------------------------  重构地址本代码  ------------------------------------*/
	
	
	init: function(rsh) {
		changeToolbarStyle('addressGroupList');
		if (this.addressCache && this.addressCache != null) {
			this.initCallback(rsh, this.addressCache);
		} else {
			mail_address({}, this.initCallback.bind(this, rsh));
		}
	},
	
	initCallback: function(rsh, ret) {
		// var _h = Element.getHeight($('left')) - 38;
		var _h = _dialog.getDimensions().height - 135;
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		var self = this;
		var html = [];
		html.push(this.groupListUI());
		html.push('<div id="mail_address_right" class="mail_address_right" style="width:'+ (getRightPanelWidth() - 194 - getMainSpaceWidth()) +'px;">');
		html.push(addr_right_area);
		html.push('</div>');
		hiddenAllPanel();
		this.ADDR.innerHTML = html.join('');
		
		// $('addgrouplist').show();
		this.contactAreaDOM = $('mail_contact_list');
		this.addressLeft = $('mail_address_left');
		this.addressRight = $('mail_address_right');
		this.mailContact = $('mail_contact');
		
		try {
			var _sprt = this.createSprEL(),
			_op = ['<div class="l-area">', this.createWriteEL(), _sprt, this.createNewEL(), _sprt, this.createAddGroupEL(), this.createEditEL(), _sprt, this.createDelEL(), '</div>'].join('');
			var _el_list = {
				top: _op + '<div class="f-rt">' + this.createSearchEL() + '</div>',
				bottom: _op
			};
		} catch(e) {}
		try {
			this.appendOperateEL(this.addressRight, _el_list);
		} catch(e) {}
		this.currentGroupId = 0;
		var _ul = this.addressLeft.getElementsByTagName('ul')[0];
		if(Element.getHeight(_ul) < _h) Element.setStyle(_ul, {height: _h + 'px'});
		Element.addClassName($('addr_group_0'), 'group_item_focus');
		
		this.mailAddrListDOM.each(function(item, index) {
			// if(contactLists[index].inContact == 0) return;
			Element.show(item);
			self.AddrList.appendChild(item);
			item.getElementsByTagName('input')[0].checked = false;
			item.lastChild.style.visibility = 'visible';
		});
		
		this.mailContact.appendChild(this.AddrList);
		this.mailAddrListDOM.each(function(item) {
			var adiv_d = item.firstChild;
			var D = new Draggable(adiv_d, {
				revert: true,
				scroll: 'sohuMailMain',
				onStart: function(element, event) {
					self.dragflag = adiv_d;
					Element.addClassName(adiv_d, 'contact_item_drag');
				},
				onDrag: function(element, event) {
					if(self._group_in) self.group_out(self._group_in);
					self._group_in = self.dropInGroup(event);
					if(self._group_in) self.group_over(self._group_in);
				},
				onEnd: function(element, event) {
					self.dragflag = false;
					Element.removeClassName(adiv_d, 'contact_item_drag');
					if(self._group_in) {
						self.group_out(self._group_in);
						var g_id = self._group_in.id.split('_');
						g_id = g_id[g_id.length-1];
						if(g_id == self.currentGroupId || g_id == -1) return;
						// self.dragflag.style.visibility = 'hidden';
						var c_id = item.id.split('_');
						c_id = c_id[c_id.length-1];
						if (self.addGroup(g_id, c_id)) {
							self.initGroup(g_id, false, true);
							self.groupsNum();
							var params = {
								id: c_id,
								newgid: g_id
							};
							var _t = setTimeout(function() {
								edit_contact(params);
								clearTimeout(_t);
								_t = null;
							}, 100);
						} else {
							_dialog.alert({info: '这个用户已经存在当前组了'});
							self.group_out(self._group_in);
						}
					}
				}
			});
			self.dragEventList.push(D);
		});
		
		Element.show(this.ADDR);
		contactCates.each(function(item) {
			var e = $('addr_group_'+item.id);
			var par = {
				el: e,
				x: e.getWidth(),
				y: e.getHeight(),
				pos: Position.cumulativeOffset(e)
			};
			self.drops.push(par);
		});
		
		if(!this.scoreCache) {
			var _emails = [];
			contactLists.each(function(item) {
				if(item.email.endsWith('@' + localPostfix)) _emails.push(item.email);
			});
			if (_emails.length > 0) {
				var params = {
					email: _emails.join(',')
				};
				get_score_addr(params, function(ret){
					this.scoreCache = ret;
					this.scoreAddr(this.scoreCache);
				}.bind(this));
			} else {
				this.scoreCache = [];
			}
		} else {
			this.scoreAddr(this.scoreCache);
		}
		// var _lh = this.addressLeft.getHeight();
		this.fixAddrHeight();
		addAjaxHistory('addressList', 'changePanel("contactList" , null, true);', '地址簿', rsh);
	},
	
	// 载入操作栏的一些功能按钮
	appendOperateEL: function(pel, list) {
		if(!list) return false;
		try {
			$('addr_opr_bar_1').innerHTML = list.top;
			$('addr_opr_bar_2').innerHTML = list.bottom;
		} catch(e) {}
		/*
		try {
			var _dl_childs = $A(pel.getElementsByTagName('dl')), _dl_top = $('addr_opr_bar_1'), _dl_bottom = $('addr_opr_bar_2');
		} catch(e) {}
		try {
			if(_dl_top) {
				list.top.each(function(item, index) {
					if(index == 0) $(item).addClassName('bt-first');
					_dl_top.appendChild(item);
				});
			}
			if(_dl_bottom) {
				list.bottom.each(function(item, index) {
					if(index == 0) $(item).addClassName('bt-first');
					_dl_bottom.appendChild(item);
				});
			}
		} catch(e) {}
		*/
	},
	
	// 修正列表界面和组列表界面的高度差
	fixAddrHeight: function() {
		Element.setStyle(this.addressRight, {height: 'auto'});
		var _rh = this.addressRight.getHeight();
		this.initLeftHeight = this.initLeftHeight ? this.initLeftHeight : this.addressLeft.getHeight();
		if((this.initLeftHeight + 30) > _rh) {
			Element.setStyle(this.addressRight, {height: (this.initLeftHeight + 30) + 'px'});
		}
	},
	
	scoreAddr: function(score_list) {
		if(!score_list || !Object.isArray(score_list)) return false;
		if(score_list.length == 0) return false;
		var confunc_score = function(s) {
			for (var i = SCORE_TYPE.length - 2; i >= 1; i -= 2)
    			if (s >= SCORE_TYPE[i]) break;
  			var img_type = SCORE_TYPE[i > 0 ? i + 1 : 0];
			var imgs = ['<a href="http://score.mail.sohu.com/faq.jsp#4" target="_blank" hidefocus="true"><span title="总积分：' + s + '" class="am score-'+ img_type[0] +'" style="float:left;cursor:pointer;"></span></a>'];
  			for (var i = img_type[1] - 1; i > 0; i--) imgs.push(imgs[0]);
			return ['<div style="padding:0px;margin-top:8px;height:16px;">', imgs.join(''), '</div>'].join('');
		};
		score_list.each(function(item) {
			var _id = 0;
			try {
				_id = this.addressHash.contact.email2id[item.email];
			} catch(e) {}
			var _el = $('addr_list_' + _id);
			if(_el) {
				try {
					_el.firstChild.lastChild.previousSibling.innerHTML = confunc_score(item.score);
				} catch(e) {}
				try {
					_el.lastChild.lastChild.previousSibling.innerHTML = confunc_score(item.score);
				} catch(e) {}
			}
		}.bind(this));
	},
	
	initFailureCallback: function() {
		_dialog.alert({info: '获取联系人信息失败！'});
	},
	
	// 创建地址簿操作的相关元素
	createSprEL: function() {
		return '<div class="f-lf"><div class="bt-sprt"></div></div>';
	},
	
	// 创建写信按钮
	createWriteEL: function() {
		var _f = arguments[0] ? 'bt-first' : '',
			_os = 'a-bg bt-common bt-2 '+ _f;
		return '<div class="f-lf s_addr_write"><div class="'+ _os +'"><div class="a-bg inner"> 写  信 </div></div></div>';
	},
	// 创建新建联系人按钮
	createNewEL: function() {
		var _f = arguments[0] ? 'bt-first' : '',
			_os = 'a-bg bt-common bt-5 '+ _f;
		return '<div class="f-lf s_addr_new"><div class="'+ _os +'"><div class="a-bg inner"> 新建联系人 </div></div></div>';
	},
	// 创建加入组按钮
	createAddGroupEL: function() {
		var _f = arguments[0] ? 'bt-first' : '',
			_os = 'a-bg bt-common bt-3 '+ _f;
		return '<div class="f-lf s_addr_add"><div class="'+ _os +'"><div class="a-bg inner"><span> 加入组 </span><b class="a-bg bt-arrow-down"></b></div></div></div>';
	},
	// 创建编辑按钮
	createEditEL: function() {
		var _f = arguments[0] ? 'bt-first' : '',
			_os = 'a-bg bt-common bt-2 '+ _f;
		return '<div class="f-lf s_addr_edit"><div class="'+ _os +'"><div class="a-bg inner"> 编  辑 </div></div></div>';
	},
	// 创建删除按钮
	createDelEL: function() {
		var _f = arguments[0] ? 'bt-first' : '',
			_os = 'a-bg bt-common bt-2 '+ _f;
		return '<div class="f-lf s_addr_del"><div class="'+ _os +'"><div class="a-bg inner"> 删  除 </div></div></div>';
	},
	// 创建搜索按钮
	createSearchEL: function() {
		return '<div style="padding-right:6px;"><img src="' + MailConst.ALL + '/spacer.gif" width="13px" height="13px" style="margin-top:6px;float:left;" class="am icon_search" align="absmiddle" /><input type="text" style="border: 1px inset #AAAAAA;width: 100px; margin-top:6px;float:left;" onkeyup="mailAddressClass.searchContact(this.value);" onblur="mailAddressClass.searchBlur(this);" /></div>';
	},
	
	// 判断地址本联系人列表数目是否超过了500
	checkAddrLimit: function() {
		// arguments[0]: 向contactLists中继续push的列表长度
		// arguments[1]: 是否显示提示信息
		var _tmp = arguments[0] ? arguments[0] : [];
		if((contactLists.length + _tmp.length) > this.addrLimit) {
			if(!arguments[1]) {
				_dialog.alert({info: this.limitInfo});
			}
			return false;
		}
		return true;
	},
	
	// 判断最近联系人列表数目是否超过了20
	checkRectLimit: function() {
		var _tmp = arguments[0] ? arguments[0] : [];
		if((recentLists.length + _tmp.length) > this.rectLimit) {
			return false;
		}
		return true;
	},
	
	// 删除黑名单中某个成员的缓存操作
	delItemByBlack: function(email) {
		if(!email || email == '') return;
		var _black_list = [];
		blackLists.each(function(item) {
			if(item.email != email) _black_list.push(item);
		});
		return _black_list;
	},
	
	// 删除白名单中某个成员的缓存操作
	delItemByWhite: function(email) {
		if(!email || email == '') return;
		var _white_list = [];
		whiteLists.each(function(item) {
			if(item.email != email) _white_list.push(item);
		});
		return _white_list;
	},
	
	// 修改最近联系人中的联系人，如果地址簿中也存在，同步地址簿中的缓存
	setAddrItemNick: function(item) {
		this.mailAddrListDOM.each(function(item_addr) {
			var _addr_id = item_addr.contact_id ? item_addr.contact_id : item_addr.getAttribute('contact_id');
			if(item.id == _addr_id) {
				item_addr.firstChild.firstChild.nextSibling.firstChild.firstChild.innerHTML = item.nickname;
				item_addr.lastChild.firstChild.nextSibling.firstChild.firstChild.innerHTML = item.nickname;
			}
		});
	},
	
	// 修改地址簿中的联系人，如果最近联系人中也存在，同步最近联系人中的缓存
	setRecentItemNick: function(item) {
		this.mailRecentListDOM.each(function(item_rect) {
			var _rect_id = item_rect.contact_id ? item_rect.contact_id : item_rect.getAttribute('contact_id');
			if(item.id == _rect_id) {
				item_rect.firstChild.firstChild.nextSibling.firstChild.firstChild.innerHTML = item.nickname;
			}
		});
	},
	
	// 生成地址本左侧组列表界面
	groupListUI: function() {
		var _html = [];
		contactCates.each(function(item) {
			var num = '(0)';
			if(item.id == 0) {
				num = '(' + contactLists.length + ')';
			} else if(item.id == -1) {
				num = '(' + recentLists.length + ')';
			} else if(item.contactid != '') {
				num = '(' + item.contactid.split(',').length + ')';
			}
			if(item.id <= 0) {
				var _data = {
					id: item.id,
					name: '<strong>' + item.name + '</strong>',
					num: '<strong>' + num + '</strong>'
				};
			} else {
				var _data = {
					id: item.id,
					name: item.name,
					num: num
				};
			}
			
			var t1 = new Template(addr_group_item).evaluate(_data);
			_html.push(t1);
		});
		var data = {
			list: _html.join('')
		}
		return new Template(addr_left_area).evaluate(data);
	},
	
	initGroup: function(id, rsh, no_rsh) {
		// DOM.sohuMailMain.focus();
		if(id == 0) {
			this.init();
			return;
		}
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		// if(!$('mail_address_left') || !$('mail_address_right')) {
			if(!Element.visible(this.ADDR)) {
				hiddenAllPanel();
				Element.show(this.ADDR);
			}
			var html = [];
			html.push(this.groupListUI());
			html.push('<div id="mail_address_right" class="mail_address_right" style="width:'+ (getRightPanelWidth() - 194 - getMainSpaceWidth()) +'px;">');
			html.push('</div>');
			this.ADDR.innerHTML = html.join('');
			this.addressLeft = $('mail_address_left');
			this.addressRight = $('mail_address_right');
		// }
		var _h = _dialog.getDimensions().height - 135;
		var _ul = this.addressLeft.getElementsByTagName('ul')[0];
		if(Element.getHeight(_ul) < _h) Element.setStyle(_ul, {height: _h + 'px'});
		this.groupItemList = [];
		var g_list = [];
		var g_obj = '';
		contactCates.each(function(item) {
			if(item.id == id) {
				g_list = item.contactid.split(',');
				g_obj = item;
			}
		});
		Element.removeClassName($('addr_group_'+this.currentGroupId), 'group_item_focus');
		Element.removeClassName($('addr_group_'+this.currentGroupId), 'group_item_over');
		Element.addClassName($('addr_group_'+id), 'group_item_focus');
		this.currentGroupId = id;
		this.addressRight.innerHTML = addr_right_area;
		this.contactAreaDOM = $('mail_contact_list');
		this.mailContact = $('mail_contact');
		try {
			var _sprt = this.createSprEL();
			if (id == -1) {
				var _op = ['<div class="l-area">', this.createWriteEL(), _sprt, this.createNewEL(), _sprt, this.createEditEL(), '</div>'].join('');
				var _el_list = {
					top: _op + '<div class="f-rt">' + this.createSearchEL() + '</div>',
					bottom: _op
				};
			}
			else {
				var _op = ['<div class="l-area">', this.createWriteEL(), _sprt, this.createNewEL(), _sprt, this.createEditEL(), _sprt, this.createDelEL(), '</div>'].join('');
				var _el_list = {
					top: _op + '<div class="f-rt">' + this.createSearchEL() + '</div>',
					bottom: _op
				};
			}
		} catch(e) {}
		try {
			this.appendOperateEL(this.addressRight, _el_list);
		} catch(e) {}
		try {
			if (this.contactAreaDOM.firstChild.nodeName.toLowerCase() != 'h3') {
				if(id == -1) {
					var data = {
						name: g_obj.name
					};
					var group_title = new Template(addr_group_option1).evaluate(data);
				} else {
					var data = {
						id: g_obj.id,
						name: g_obj.name
					};
					var group_title = new Template(addr_group_option).evaluate(data);
				}
				var h3 = document.createElement('h3');
				h3.innerHTML = group_title;
				Element.insert(this.contactAreaDOM, {
					top: h3
				});
			}
		} catch(e) {}
		var self = this;
		if (id == -1) {
			// this.groupItemList = this.mailRecentListDOM;
			this.groupItemList = [];
			this.mailRecentListDOM.each(function(item) {
				Element.show(item);
				self.AddrList.appendChild(item);
				item.getElementsByTagName('input')[0].checked = false;
				item.lastChild.style.visibility = 'hidden';
			});
		} else {
			g_list.each(function(item){
				self.mailAddrListDOM.each(function(_item){
					if ('addr_list_' + item == _item.id) {
						Element.show(_item);
						self.groupItemList.push(_item);
						self.AddrList.appendChild(_item);
						_item.getElementsByTagName('input')[0].checked = false;
						_item.lastChild.style.visibility = 'hidden';
					}
				});
			});
		}
		this.mailContact.appendChild(this.AddrList);
		this.groupItemList.each(function(item) {
			var adiv_d = item.firstChild;
			var D = new Draggable(adiv_d, {
				revert: true,
				scroll: 'sohuMailMain',
				onStart: function(element, event) {
					self.dragflag = adiv_d;
					Element.addClassName(adiv_d, 'contact_item_drag');
					if(self.ctrl_down || id == -1) adiv_d.nextSibling.style.visibility = 'visible';
				},
				onDrag: function(element, event) {
					if(self._group_in) self.group_out(self._group_in);
					self._group_in = self.dropInGroup(event);
					if(self._group_in) self.group_over(self._group_in);
				},
				onEnd: function(element, event) {
					self.dragflag = false;
					Element.removeClassName(adiv_d, 'contact_item_drag');
					adiv_d.nextSibling.style.visibility = 'hidden';
					if(self._group_in) {
						self.group_out(self._group_in);
						var g_id = self._group_in.id.split('_');
						g_id = g_id[g_id.length-1];
						if(g_id == self.currentGroupId || g_id == -1) return;
						// self.dragflag.style.visibility = 'hidden';
						var c_id = item.id.split('_');
						c_id = c_id[c_id.length-1];
						
						var __flag = false;
						recentLists.each(function(item) {
							if(item.id == c_id && item.inContact == 0) __flag = true;
						});
						if(__flag) {
							_dialog.alert({info: '请先将该联系人添加到地址簿中！'});
							return;
						}
						
						self._addGroup(self.currentGroupId, g_id, c_id);
						self.groupsNum();
					}
				}
			});
			self.dragEventList.push(D);
		});
		
		var _op = $('mail_contact_list').getElementsByTagName('span')[0];
		if(!Element.visible(_op)) {
			Element.show(_op)
		}
		
		this.scoreAddr(this.scoreCache);
		// 生成组列表的时候，如果添加了历史记录，在IE下会影响拖拽的效果（不会对功能上有影响，只是用户的体验有些不好）
		// if(!no_rsh) addAjaxHistory('addressGroup_' + id, 'changePanel("contactCate" ,'+ id +' , true);', '联系组：' + g_obj.name, rsh);
		
		// var _lh = this.addressLeft.getHeight();
		this.fixAddrHeight();
	},
	
	addsGroup: function(group_id, list) {
		var _list = list ? list : this.getChecked();
		if (_list.length == 0) {
			_dialog.alert({info: '请选择需要操作的联系人'});
			return false;
		}
		var __list = [].concat(_list);
		this.addGroup(group_id, _list);
		var _t = setTimeout(function() {
			var params = {
				id: __list.join(','),
				newgid: group_id
			};
			edit_contact(params);
			clearTimeout(_t);
			_t = null;
		}, 100);
		return true;
	},
	
	// 将联系人从所有组中添加到某一个组中（所有联系人组中不删除这个联系人，目标组中添加联系人）
	addGroup: function(group_id, contact_id) {
		if(typeof contact_id == 'object' && contact_id.length > 0) {
			this.addGroup(group_id, contact_id[0]);
			contact_id.shift();
		}
		var flag = false;
		contactCates.each(function(item) {
			if(item.id == group_id && !item.contactid.include(contact_id)) {
				item.contactid = item.contactid == '' ? contact_id + '' : contact_id+','+item.contactid;
				flag = true;
			}
		});
		return flag;
	},
	
	// 将联系人从某一个组中移动到另一个组中（当前联系人将从源组中删除，添加到目标组中）
	_addGroup: function(s_group_id, d_group_id, contact_id) {
		var self = this;
		var confunc_add = function() {
			var params = {
				id: contact_id
			};
			contactCates.each(function(item) {
				if(item.id == s_group_id && item.contactid.include(contact_id)) {
					if (!self.ctrl_down) {
						var _it = item.contactid.split(',');
						_it.splice(_it.indexOf(contact_id), 1);
						item.contactid = _it.join(',');
						params.gid = s_group_id;
					}
				} else if (item.id == d_group_id && !item.contactid.include(contact_id)) {
					item.contactid = item.contactid == '' ? contact_id+'' : contact_id+','+item.contactid;
					params.newgid = d_group_id;
				}
			});
			self.initGroup(d_group_id);
			var _t = setTimeout(function() {
				edit_contact(params);
				clearTimeout(_t);
				_t = null;
			}, 100);
		};
		if (!self.ctrl_down) {
			if(d_group_id == 0) {
				_dialog.confirm({
					info: '组 <b>所有联系人</b> 中已包含此联系人, 您要把它从当前组中删除吗？',
					click: function(){
						confunc_add();
					}
				});
				return;	
			}
			for (var i = 0; i < contactCates.length; i++) {
				var item = contactCates[i];
				if (item.id == d_group_id && item.contactid.include(contact_id)) {
					_dialog.confirm({
						info: '组 <b>' + item.name + '</b> 中已包含此联系人, 您要把它从当前组中删除吗？',
						click: function(){
							confunc_add();
						}
					});
					return;
				}
			}
		}
		confunc_add();
	},
	
	group_over: function(el) {
		if(el == $('addr_group_'+this.currentGroupId)) return;
		Element.addClassName(el, 'group_item_over');
	},
	
	group_out: function(el) {
		if(el == $('addr_group_'+this.currentGroupId)) return;
		try {
			Element.removeClassName(el, 'group_item_over');
		} catch(e) {}
	},
	
	contact_over: function(el) {
		if(this.dragflag) return;
		Element.addClassName(el, 'contact_item_over');
	},
	
	contact_out: function(el) {
		try {
			Element.removeClassName(el, 'contact_item_over');
		} catch(e) {}
	},
	
	clearList: function(el) {
		this.mailAddrListDOM.each(function(item) {
			if(item.parentNode) {
				item.parentNode.removeChild(item);
			}
		});
		this.mailRecentListDOM.each(function(item) {
			if(item.parentNode) {
				item.parentNode.removeChild(item);
			}
		});
		try {
			var _mcl = $('mail_contact_list');
			if (_mcl) {
				var h3 = $A(_mcl.getElementsByTagName('h3'));
				if (h3.length > 0) {
					h3.each(function(item){
						_mcl.removeChild(item);
					});
				}
			}
		} catch(e) {}
	},
	
	clearDragEvent: function() {
		this.dragEventList.each(function(item) {
			try {
				item.destroy();
				item = null;
			} catch(e) {}
		});
		this.dragEventList = [];
	},
	
	// 判断拖拽的鼠标是否进入到某一个组中
	dropInGroup: function(event) {
		var pointer = Event.pointer(event);
		pointer.y = pointer.y + this.sohuMailMain.scrollTop;
		var flag = false;
		this.drops.each(function(item) {
			if(pointer.x > item.pos[0] && pointer.y > item.pos[1] && pointer.x < (item.pos[0]+item.x) && pointer.y < (item.pos[1]+item.y)) {
				flag = item.el;
			}
		});
		return flag;
	},
	
	// 新建组界面展示
	createGroup: function(rsh) {
		this.groupDragList = [];
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		this._current_contact = null;
		Element.removeClassName($('addr_group_'+this.currentGroupId), 'group_item_focus');
		
		if(!$('mail_address_left') || !$('mail_address_right')) {
			if(!Element.visible(this.ADDR)) {
				hiddenAllPanel();
				Element.show(this.ADDR);
			}
			var html = [];
			html.push(this.groupListUI());
			html.push('<div id="mail_address_right" class="mail_address_right" style="width:'+ (getRightPanelWidth() - 194 - getMainSpaceWidth()) +'px;">');
			html.push('</div>');
			this.ADDR.innerHTML = html.join('');
			this.addressLeft = $('mail_address_left');
			this.addressRight = $('mail_address_right');
		}
		
		this.currentGroupId = -2;
		var g_contact = '';
		var g_name = '';
		if(arguments[1]) {
			var arg = arguments[1];
			if (typeof arg != 'object') {
				contactCates.each(function(item){
					if (item.id == arg) {
						g_contact = item.contactid;
						g_name = item.name;
					}
				});
				this._edit_group = arg;
			} else {
				g_contact = arg.join(',');
			}
		} else {
			this._edit_group = false;
		}
		var data = {};
		var _t = new Template(mailAddrCreateGroupTemplate);
		var _s = [];
		var _ss = [], _dd = [];
		contactLists.each(function(item) {
			if (g_contact.include(item.id)) {
				_dd.push(new Template(addr_group_add_item).evaluate({id: item.id, email: item.email, nickname: item.nickname}));
			} else {
				_ss.push(new Template(addr_group_add_item).evaluate({id: item.id, email: item.email, nickname: item.nickname}));
			}
		});
		_s.push('<div id="group_list_s" class="group_list_add"><div style="width:100%;height:auto;">');
		_s.push(_ss.join(''));
		_s.push('</div></div>');
		var _d = [];
		_d.push('<div id="group_list_d" class="group_list_add"><div style="width:100%;height:auto;">');
		_d.push(_dd.join(''));
		_d.push('</div></div>');
		data['groupname'] = g_name;
		data['sitem'] = _s.join('');
		data['ditem'] = _d.join('');
		this.addressRight.innerHTML = _t.evaluate(data);
		this.gls = $('group_list_s');
		this.gld = $('group_list_d');
		var self = this;
		$A(this.gls.firstChild.childNodes).each(function(item) {
			if(item.nodeName.toLowerCase() != 'div') return;
			var _it = item.firstChild;
			var D = self.bindDrag(null, item, _it, [self.gls, self.gld]);
			self.groupDragList.push(D);
		});
		$A(this.gld.firstChild.childNodes).each(function(item) {
			if(item.nodeName.toLowerCase() != 'div') return;
			var _it = item.firstChild;
			var D = self.bindDrag(null, item, _it, [self.gld, self.gls]);
			self.groupDragList.push(D);
		});
		
		var __el = $('newGroupName');
		this.listenEntryKey(__el, this.createG.bind(this));
		this.current_focus_el = __el;
		var __t = setTimeout(function() {
			clearTimeout(__t);
			__t = null;
			__el.focus();
		}, 100);
		addAjaxHistory('createGroup', 'mailAddressClass.createGroup(true);', '创建组', rsh);
	},
	
	_add: function() {
		var _confunc_add = function(el) {
			if(Element.descendantOf(el, this.gls)) {
				Element.insert(this.gld.firstChild, {top: el.parentNode});
				var D = this.bindDrag(null, el.parentNode, el, [this.gld, this.gls]);
				this.groupDragList.push(D);
			}
		}.bind(this);
		if(this._current_contact) {
			_confunc_add(this._current_contact);
			Element.removeClassName(this._current_contact, 'listover');
		}
		if(this._current_contact_lists) {
			this._current_contact_lists.each(function(item) {
				_confunc_add(item);
				Element.removeClassName(item, 'listover');
			}.bind(this));
		}
		this._current_contact_lists = [];
		try {
			this._current_contact = this.gls.firstChild.firstChild.firstChild;
			Element.addClassName(this._current_contact, 'listover');
		} catch(e) {
			this._current_contact = null;
		}
	},
	
	_delete: function() {
		var _confunc_del = function(el) {
			if(Element.descendantOf(el, this.gld)) {
				Element.insert(this.gls.firstChild, {top: el.parentNode});
				var D = this.bindDrag(null, el.parentNode, el, [this.gls, this.gld]);
				this.groupDragList.push(D);
			}
		}.bind(this);
		if(this._current_contact) {
			_confunc_del(this._current_contact);
			Element.removeClassName(this._current_contact, 'listover');
		}
		if(this._current_contact_lists) {
			this._current_contact_lists.each(function(item) {
				_confunc_del(item);
				Element.removeClassName(item, 'listover');
			}.bind(this));
		}
		this._current_contact_lists = [];
		try {
			this._current_contact = this.gld.firstChild.firstChild.firstChild;
			Element.addClassName(this._current_contact, 'listover');
		} catch(e) {
			this._current_contact = null;
		}
	},
	
	clearGroupDragEvent: function() {
		if(!this.groupDragList) return;
		if (this.groupDragList && this.groupDragList.length == 0) return;
		this.groupDragList.each(function(item) {
			try {
				item.destroy();
				item = null;
			} catch(e) {}
		});
		this.groupDragList = [];
	},
	
	listmousedown: function(el) {
		if (this.ctrl_down) {
			if (!this._current_contact_lists) 
				this._current_contact_lists = [];
			this._current_contact_lists.push(el);
			Element.addClassName(el, 'listover');
		} else {
			if(this._current_contact_lists) {
				this._current_contact_lists.each(function(item) {
					Element.removeClassName(item, 'listover');
				});
				this._current_contact_lists = [];
			}
			if (this._current_contact) {
				Element.removeClassName(this._current_contact, 'listover');
			}
			this._current_contact = el;
			Element.addClassName(el, 'listover');
		}
	},
	
	listover: function(el) {
		if(this._current_contact_lists) {
			var _flag = false;
			this._current_contact_lists.each(function(item) {
				if(item == el) _flag = true;
			});
			if(_flag) return;
		}
		if(this._current_contact == el) return;
		Element.addClassName(el, 'listover');
	},
	
	listout: function(el) {
		if(this._current_contact_lists) {
			var _flag = false;
			this._current_contact_lists.each(function(item) {
				if(item == el) _flag = true;
			});
			if(_flag) return;
		}
		if(this._current_contact == el) return;
		Element.removeClassName(el, 'listover');
	},
	
	// 创建组的时候，在联系人列表中拖拽事件的绑定与销毁
	bindDrag: function(drag, item, _it, el) {
		if(drag && drag != null) {
			drag.destroy();
			drag = null;
		}
		var self = this;
		drag = new SubsDraggable(_it, {
			_scroll: el[0],
			onStart: function(element, event) {
				self.sohuMailMain.appendChild(_it);
			},
			onEnd: function(element, event) {
				with(_it.style){
					left = '0px';
					top = '0px';
				};
				item.appendChild(_it);
				var pointer = Event.pointer(event);
				var _el = el[1];
				var is_in = Position.withinIncludingScrolloffsets(_el, pointer.x, pointer.y);
				if(is_in) {
					Element.insert(_el.firstChild, {top: item});
					drag.destroy();
					drag = null;
					self.bindDrag(drag, item, _it, [el[1], el[0]]);
					if(self._current_contact_lists) self._current_contact_lists = [];
					/*
					if(self._current_contact || self._current_contact_lists) {
						Element.removeClassName(self._current_contact, 'listover');
						self._current_contact = null;
						if (self._current_contact_lists) {
							self._current_contact_lists.each(function(item) {
								Element.removeClassName(item, 'listover');
							});
							self._current_contact_lists = [];
						}
					}
					*/
				}
			}
		});
		return drag;
	},
	
	// 开始创建组
	createG: function() {
		var g_name = this.checkGroupName($('newGroupName'));
		var g_contact = [];
		$A(this.gld.firstChild.childNodes).each(function(item) {
			var id = item.contact_id ? item.contact_id : item.getAttribute('contact_id');
			if(id) g_contact.push(id);
		});
		
		if(g_name == '') return;
		if(g_contact.length == 0) {
			_dialog.alert({info: '请选择联系人'});
			return;
		}
		if (!this._edit_group) {
			var params = {
				ncGroup: g_contact.join(','),
				groupname: g_name
			};
			add_group(params, this.createGcallback.bind(this, params));
		} else {
			var params = {
				gid: this._edit_group,
				ncGroup: g_contact.join(','),
				groupname: g_name
			};
			edit_group(params, this.editGcallback.bind(this, params));
		}
	},
	
	createGcallback: function(params, ret) {
		if(ret.status == true) {
			var par = {
				contactid: params.ncGroup,
				id: ret.msg,
				name: params.groupname,
				pinyin: ''
			};
			contactCates.push(par);
			
			var num = '(0)';
			if(params.ncGroup != '') {
				num = '(' + params.ncGroup.split(',').length + ')';
			}
			var g_item = '<li onmouseover="mailAddressClass.group_over(this);" onmouseout="mailAddressClass.group_out(this);" onclick="mailAddressClass.initGroup('+ ret.msg +');" id="addr_group_'+ ret.msg +'" style="white-space:nowrap; width: 100%;"><div style="margin: auto 10px; overflow: hidden; width: 160px; line-height: 24px; white-space: nowrap;"> '+ params.groupname +' <span> '+ num +' </span></div></li>';
			// var last_li = this.addressLeft.getElementsByTagName('ul')[0].getElementsByTagName('li');
			// Element.insert(last_li[last_li.length-1], {bottom: g_item});
			var _last = $A(this.addressLeft.getElementsByTagName('ul')[0].getElementsByTagName('li'));
			var _last_li = _last[_last.length - 1];
			var self = this;
			// var _t = setTimeout(function() {
			// 	clearTimeout(_t);
			// 	_t = null;
				Element.insert(_last_li, {after: g_item});
				this.initGroup(ret.msg);
				this.showMsg();
			// }, 100);
			
		} else {
			_dialog.alert({info: ret.msg});
		}
	},
	
	createGfailureCallback: function() {
		_dialog.alert({info: '创建组失败'});
	},
	
	editGcallback: function(params, ret) {
		if(ret.status == true) {
			var par = {
				contactid: params.ncGroup,
				id: params.gid,
				name: params.groupname,
				pinyin: ''
			};
			contactCates.each(function(item) {
				if(item.id == par.id) {
					with(item) {
						contactid = par.contactid;
						name      = par.name;
						pinyin    = par.pinyin;
					};
				}
			});
			var num = '(0)';
			if(params.ncGroup != '') {
				num = '(' + params.ncGroup.split(',').length + ')';
			}
			var c_el = $('addr_group_'+params.gid);
			// var g_item = '<li onmouseover="mailAddressClass.group_over(this);" onmouseout="mailAddressClass.group_out(this);" onclick="mailAddressClass.initGroup('+ params.gid +');" id="addr_group_'+ params.gid +'" style="white-space:nowrap; width: 100%;"><div style="margin: auto 10px; overflow: hidden; width: 160px; line-height: 24px; white-space: nowrap;"></div></li>';
			c_el.firstChild.innerHTML = params.groupname +' <span> '+ num +' </span>';
			this.initGroup(params.gid);
			this.showMsg();
		} else {
			_dialog.alert({info: ret.msg});
		}
	},
	
	editGfailureCallback: function() {
		
	},
	
	deleteG: function(id) {
		var params = {
			gid: id
		};
		del_group(params, function(ret) {
			if(ret.status) this.showMsg();
		}.bind(this));
	},
	
	// 维护组成员数量的事件
	groupsNum: function() {
		contactCates.each(function(item) {
			if(item.id != -1 && item.id != 0) {
				var _c = item.contactid == '' ? 0 : item.contactid.split(',').length;
				$('addr_group_' + item.id).firstChild.lastChild.innerHTML = '('+ _c +')';
			}
		});
	},
	
	// 给组发信/给某个联系人发信
	groupWriteMail: function(g_name) {
		changePanel('composeMail');
		writemail.addressbook_use_flag = 1;
		DOM.compose_wto.value = g_name + ', ';
		writemail.to = g_name + ', ';
	},
	
	// 给多个联系人发信
	contactsWriteMail: function() {
		var _list = this.getChecked();
		if(_list.length == 0) {
			_dialog.alert({info: '请选择联系人'});
			return;
		}
		var _l = [];
		var _tmp_lists = [];
		if(this.currentGroupId == -1) {
			_tmp_lists = recentLists;
		} else {
			_tmp_lists = contactLists;
		}
		_tmp_lists.each(function(item) {
			if(_list.include(item.id)) {
				_l.push(item.email);
			}
		});
		changePanel('composeMail');
		writemail.addressbook_use_flag = 1;
		DOM.compose_wto.value = _l.join(', ') + ', ';
		writemail.to = _l.join(', ') + ', ';
	},
	
	// 删除组
	deleteGroup: function(g_id) {
		var confunc_del = function(g_id) {
			var i = 0;
			contactCates.each(function(item, index) {
				if(item.id == g_id) {
					i = index;
				}
			});
			contactCates.splice(i, 1);
			this.init();
			this.deleteG(g_id);
		}.bind(this);
		_dialog.confirm({info: '确定要删除当前组？', click: function() {
			confunc_del(g_id);
		}});
	},
	
	// 删除联系人（联系人可以进行多个同时删除）
	deleteContact: function() {
		var c_id_list = [];
		if(arguments[0]) {
			if (typeof arguments[0] == 'object') {
				c_id_list = arguments[0];
			} else {
				var _id;
				if(arguments[0].indexOf('@') == -1) {
					_id = arguments[0];
				} else {
					var _email = arguments[0];
					contactLists.each(function(item) {
						if(_email == item.email) _id = item.id
					});
				}
				if(_id) c_id_list.push(_id);
			}
		} else {
			c_id_list = this.getChecked();
			if(c_id_list.length == 0) {
				_dialog.alert({info: '请选择要删除的联系人'});
				return;
			}
		}
		if(arguments[1]) var no_request = true;
		var self = this;
		var confunc_delc = function() {
			c_id_list.each(function(item) {
				// 从缓存的DOM中删除
				var i1 = 0;
				self.mailAddrListDOM.each(function(_item, index) {
					if(_item.id == 'addr_list_' + item) {
						i1 = index;
						try {
							var __el = $('addr_list_' + item);
							if(__el) var pn = __el.parentNode;
							if (pn) {
								pn.removeChild($('addr_list_' + item));
							}
						} catch(e) {}
					}
				});
				var dd = self.mailAddrListDOM.splice(i1, 1);
				dd = null;
				// 从缓存的contactLists中删除
				var i2 = 0;
				contactLists.each(function(_item, index) {
					if(_item.id == item) {
						i2 = index;
					}
				});
				contactLists.splice(i2, 1);
				// 从缓存的contactCates中删除
				contactCates.each(function(_item) {
					if(_item.contactid.include(item)) {
						var _a = _item.contactid.split(',');
						_a = _a.without(item);
						_item.contactid = _a.join(',');
					}
				});
			});
			if(no_request) return;
			self.init();
			del_contact({id: c_id_list.join(',')}, function(ret) {
				if(ret.status) self.showMsg();
			}.bind(self));
		};
		var confuncgroup_delc = function() {
			if(self.currentGroupId == 0) return;
			c_id_list.each(function(item) {
				contactCates.each(function(_item) {
					if(_item.id == self.currentGroupId && _item.contactid.include(item)) {
						var _a = _item.contactid.split(',');
						_a = _a.without(item);
						_item.contactid = _a.join(',');
					}
				});
			});
			self.initGroup(self.currentGroupId);
			self.groupsNum();
			edit_contact({id: c_id_list.join(','), gid: self.currentGroupId}, function(ret) {
				if(ret.status) self.showMsg();
			}.bind(self));
		};
		if (!arguments[0]) {
			_dialog.confirm({
				info: '确定要删除选中的联系人？',
				click: function(){
					if (self.currentGroupId == 0) {
						confunc_delc();
					} else {
						confuncgroup_delc();
					}
				}
			});
		} else {
			var _t = setTimeout(function() {
				clearTimeout(_t);
				_t = null;
				confunc_delc();
			}, 100);
		}
	},
	
	// 创建联系人界面显示
	createContact: function(rsh) {
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		this._edit_contact = null;
		var data = [];
		data['ncName'] = "";
		data['ncNick'] = "";
		data['ncFmail'] = "";
		data['ncBmail'] = "";
		data['ncMobile'] = "";
		data['ncHP'] = "";
		data['ncOP'] = "";
		data['ncF'] = "";
		data['ncPager'] = "";
		data['ncH'] = "";
		data['ncHPost'] = "";
		data['ncO'] = "";
		data['ncOPost'] = "";
		data['ncYear'] = "";
		data['ncMonth'] = "";
		data['ncDay'] = "";
		data['ncNote'] = "";
		data['ncPage'] = "";
        //新手上路的垃圾js,alva
        try{
            if(parseInt(arguments[1]) == 1){
                this.is_tourial = true;
            }
        }
        catch(e){
        }

		var _g = [];
		contactCates.each(function(item) {
			if(item.id <= 0) return;
			_g.push('<input id="ncGroup' + item.id +'" type="checkbox" name="ncGroup' + item.id + '" value="' + item.id + '" />' + item.name);
		});
		data['groupBox'] = _g.join('');
		var mailAddrCreateContact = new Template(mailAddrCreateContactTemplate);
		DOM.addressGroupList.innerHTML = mailAddrCreateContact.evaluate(data);
		
		
		var name = toTrimDBC($('ncName').value.strip()).toLowerCase();
		var nick = toTrimDBC($('ncNick').value.strip()).toLowerCase();
		var fmail = toTrimDBC($('ncFmail').value.strip()).toLowerCase();
		var bmail = toTrimDBC($('ncBmail').value.strip()).toLowerCase();
		var mobile = toTrimDBC($('ncMobile').value.strip()).toLowerCase();
		var hp = toTrimDBC($('ncHP').value.strip()).toLowerCase();
		var op = toTrimDBC($('ncOP').value.strip()).toLowerCase();
		var f = toTrimDBC($('ncF').value.strip()).toLowerCase();
		var pager = toTrimDBC($('ncPager').value.strip()).toLowerCase();
		var h = toTrimDBC($('ncH').value.strip()).toLowerCase();
		var hpost = toTrimDBC($('ncHPost').value.strip()).toLowerCase();
		var o = toTrimDBC($('ncO').value.strip()).toLowerCase();
		var opost = toTrimDBC($('ncOPost').value.strip()).toLowerCase();
		var year = toTrimDBC($('ncYear').value.strip()).toLowerCase();
		var month = toTrimDBC($('ncMonth').value.strip()).toLowerCase();
		var day = toTrimDBC($('ncDay').value.strip()).toLowerCase();
		var note = toTrimDBC($('ncNote').value.strip()).toLowerCase();
		var page = toTrimDBC($('ncPage').value.strip()).toLowerCase();
		
		var __el = $('ncNick');
		var _elements = [__el, $('ncFmail'), $('ncBmail'), $('ncMobile'), $('ncHP'), $('ncOP'), $('ncF'), $('ncPager'), $('ncH'), $('ncHPost'), $('ncO'), $('ncOPost'), $('ncYear'), $('ncMonth'), $('ncDay'), $('ncNote'), $('ncPage')];
		this.listenEntryKey(_elements, this.createC.bind(this));
		this.current_focus_el = __el;
		var __t = setTimeout(function() {
			clearTimeout(__t);
			__t = null;
			__el.focus();
		}, 100);
		$('ncYear').onblur = function() {
			if(this.value != '') {
				var _y = new Date().getFullYear();
				if(this.value > (_y - 16)) {
					var _d = this.parentNode.lastChild;
					_d.style.display = '';
					var __t = setTimeout(function() {
						clearTimeout(__t);
						__t = null;
						_d.style.display = 'none';
					}, 3000);
				}
			}
		};
		addAjaxHistory("createContact","mailAddressClass.createContact(true);", "新建联系人", rsh);
	},
	
	listenEntryKey: function(elements, _event) {
		if (elements instanceof Array) {
			elements.each(function(item) {
				Event.observe(item, 'keydown', function(event) {
					if (event.keyCode == 13) {
						_event();
					}
				});
			});
		} else {
			Event.observe(elements, 'keydown', function(event) {
				if (event.keyCode == 13) {
					_event();
				}
			});
		}
	},
	
	// 获取联系人的详细信息
	getC: function(id) {
		if(!id) {
			_dialog.alert({info: '请选择需要编辑的联系人'});
			return;
		}
		get_d_contact({id: id}, this.getCcallback.bind(this, id), this.getCfailureCallback.bind(this));
		// 加入oplog
		try {
			jsoplog.ucCapture('addredit');
		} catch(e) {}
	},
	
	getCcallback: function(id, ret) {
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		var data = [];
		this._edit_contact = id;
		var _V = function(v) {
			return v ? v : '';
		};
		
		data['ncName']   = _V(ret.fullname);
		data['ncNick']   = _V(ret.nickname);
		data['ncFmail']  = _V(ret.personalemail);
		data['ncBmail']  = _V(ret.otheremail);
		data['groupBox'] = "";
		data['ncMobile'] = _V(ret.mobilephone);
		data['ncHP']     = _V(ret.otherphone);
		data['ncOP']     = _V(ret.businessphone);
		data['ncF']      = _V(ret.fax);
		data['ncPager']  = _V(ret.pager);
		data['ncH']      = _V(ret.personalstreet);
		data['ncHPost']  = _V(ret.personalzip);
		data['ncO']      = _V(ret.businessstreet);
		data['ncOPost']  = _V(ret.businesszip);
		data['ncYear']   = parseInt(_V(ret.birthday).split("-")[0]) != 0
				? _V(ret.birthday).split("-")[0]
				: "";
		data['ncMonth']  = parseInt(_V(ret.birthday).split("-")[1]) != 0
				? _V(ret.birthday).split("-")[1]
				: "";
		data['ncDay']    = parseInt(_V(ret.birthday).split("-")[2]) != 0
				? _V(ret.birthday).split("-")[2]
				: "";
		data['ncNote']   = _V(ret.notes);
		data['ncPage']   = _V(ret.homepage);
		
		var _g = [];
		contactCates.each(function(item){
			if (item.id <= 0) 
				return;
			var ck = ret.ncGroup ? (ret.ncGroup.include(item.id) ? ' checked ' : '') : '';
			_g.push('<input id="ncGroup' + item.id + '" type="checkbox"'+ ck +' name="ncGroup' + item.id + '" value="' + item.id + '" />' + item.name);
		});
		data['groupBox'] = _g.join('');
		var mailAddrCreateContact = new Template(mailAddrCreateContactTemplate);
		DOM.addressGroupList.innerHTML = mailAddrCreateContact.evaluate(data);
		$('ncYear').onblur = function() {
			if(this.value != '') {
				var _y = new Date().getFullYear();
				if(this.value > (_y - 16)) {
					var _d = this.parentNode.lastChild;
					_d.style.display = '';
					var __t = setTimeout(function() {
						clearTimeout(__t);
						__t = null;
						_d.style.display = 'none';
					}, 3000);
				}
			}
		};
	},
	
	getCfailureCallback: function() {
		
	},
	
	// 获取选中的用户联系人列表
	getChecked: function() {
		var _list = [];
		$A(this.mailContact.firstChild.childNodes).each(function(item) {
			if(item.nodeName.toLowerCase() != 'div' || !Element.visible(item)) return;
			if(item.getElementsByTagName('input')[0].checked)
				_list.push(item.contact_id ? item.contact_id : item.getAttribute('contact_id'));
		});
		return _list;
	},
	
	setAll: function(checked) {
		if(!this.mailContact) return;
		$A(this.mailContact.firstChild.childNodes).each(function(item) {
			if(item.nodeName.toLowerCase() != 'div') return;
			item.getElementsByTagName('input')[0].checked = checked;
		});
	},
	
	// 创建联系组的时候，组名的判断， 返回一个字符串
	checkGroupName : function(groupname) {
		var gn = toTrimDBC(groupname.value.strip().toLowerCase());
		var __flag = false;
		contactCates.each(function(item) {
			if(item.name == gn && item.id != this._edit_group) __flag = true;
		}.bind(this));
		if(__flag) {
			_dialog.alert({info: '该联系组名称已存在，请修改名称后提交！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return '';
		}
		if (gn.blank()) {
			_dialog.alert({info: '请输入联系组名称！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return '';
		}
		if (gn.include(' ')) {
			_dialog.alert({info: '联系组名不能含空格！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return '';
		}
		if (this._check_length(gn) > 20) {
			_dialog.alert({info: '联系组名太长！请限制在10个汉字或20个英文字母以内！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return '';
		}
		if (!checkSpecial(gn)) {
			return '';
		}
		return gn;
	},
	
	_check_length: function(str) {
		var len = str.length;
		var l = 0;
		for (var i = 0; i < len; i++) {
			if (str.charCodeAt(i) > 255 || str.charCodeAt(i) < 0) {
				l += 2;
			} else {
				l ++;
			}
		}
		return l;
	},
	
	// 创建联系人界面的显示/隐藏
	switchInfoPanel : function(_imgEle, _panelName) {
		if (!$(_panelName).visible()) {
			$(_panelName).show();
			_imgEle.src = MailConst.ALL + '/icon_arrow_top.gif';
		} else {
			$(_panelName).hide();
			_imgEle.src = MailConst.ALL + '/icon_arrow_bottom.gif';
		}
	},
	
	// 创建联系人
	createC: function() {
		this.currentGroupId = 0;
		var pars = this.checkContactPars();
		if (pars.length == 0) {
			return;
		}
		var params = {
			fullname : pars[0],
			nickname : pars[1],
			personalemail : pars[2],
			otheremail : pars[3],
			ncGroup : pars[4],
			mobilephone : pars[5],
			otherphone : pars[6],
			businessphone : pars[7],
			fax: pars[8],
			personalstreet : pars[9],
			personalzip : pars[10],
			businessstreet : pars[11],
			businesszip : pars[12],
			birthday : pars[13],
			notes : pars[14],
			homepage : pars[15]
		};
		
        var confunc_contact = function() {
            if (this._edit_contact && this._edit_contact != null) {
                params.id = this._edit_contact;
                var _is_re = false;
				var _edit_id = 0;
                contactLists.each(function(item){
                    if (item.id != params.id && item.email == params.personalemail) {
						_is_re = true;
						_edit_id = item.id;
					}
                });
                if (_is_re) {
                    var self = this;
					params.old_id = params.id;
					params.id = _edit_id;
                    _dialog.confirm({
                        info: '当前邮件地址已经有一条联系人记录了，是否要替换老的记录？',
                        click: function(){
							// self.deleteContact(params.personalemail);
                            edit_d_contact(params, self.createCcallback.bind(self, params));
                        }
                    });
                    return;
                }
                else {
                    edit_d_contact(params, this.createCcallback.bind(this, params));
                }
            }
            else {
                add_d_contact(params, this.createCcallback.bind(this, params), this.createCfailureCallback.bind(this));
            }
        }.bind(this);
		
		var in_blacklist = false;
		blackLists.each(function(item) {
			if(item.email == pars[2]) in_blacklist = true;
		});
		if(in_blacklist) {
			_dialog.confirm({info: '该地址在黑名单中，添加到地址簿会将其从黑名单删除，是否继续？', click: function() {
				confunc_contact();
				var _black_list = [];
				blackLists.each(function(item) {
					if(item.email != pars[2]) _black_list.push(item);
				});
				blackLists = _black_list;
			}});
			return;
		}
		confunc_contact();
	},
	
	createCcallback: function(params, ret) {
		
        //新手上路 .alva
        //只要从服务器回来,就该给用户积分.
        if(this.is_tourial){
        	var __tou__ = setTimeout(function(ret){
				clearTimeout(__tou__);
                __tou__ = null;
				try {
					get_newbee_type('complete_mission', 'add_contact', 1);
				} catch(e) {}
            }, 100);
        }
        
		if(ret.status == true) {
			var _id, _pinyin;
			if(typeof ret.msg == 'object') {
				_id = ret.msg.id;
				_pinyin = ret.msg.pinyin;
			} else {
				_id = ret.msg;
				_pinyin = ret.pinyin;
			}
			var par = {
				email: params.personalemail,
				id: _id,
				isRecent: 0,
				nickname: params.nickname,
				pinyin: _pinyin
			};
			if (params.id) {
				// var tmp_id;
				contactLists.each(function(item) {
					// if(item.email == par.email && item.id != params.id) tmp_id = item.id;
					if(item.id == params.id) {
						with(item) {
							email = par.email;
							isRecent = par.isRecent;
							nickname = par.nickname;
							pinyin = par.pinyin;
						};
					}
				});
				this.mailAddrListDOM.each(function(item) {
					var c_id = item.contact_id ? item.contact_id : item.getAttribute('contact_id');
					if(c_id == params.id) {
						item.firstChild.getElementsByTagName('div')[1].getElementsByTagName('span')[0].innerHTML = params.nickname;
						item.lastChild.getElementsByTagName('div')[1].getElementsByTagName('span')[0].innerHTML = params.nickname;
						item.firstChild.lastChild.innerHTML = params.personalemail;
						item.lastChild.lastChild.innerHTML = params.personalemail;
					}
				});
				if(params.old_id) {
					this.deleteContact(params.old_id);
				}
			} else {
				contactLists.push(par);	
				var adiv = this.createListItem(par);
				this.mailAddrListDOM.push(adiv);
			}
			contactCates.each(function(item) {
				if(item.id < 1) return;
				if(item.contactid.include(_id) && !params.ncGroup.include(item.id)) {
					var _l = item.contactid.split(',');
					var _new_l = [];
					_l.each(function(__item) {
						if(__item != _id) _new_l.push(__item);
					});
					item.contactid = _new_l.join(',');
				}
				if (params.ncGroup.include(item.id) && !item.contactid.include(_id)) {
					item.contactid = item.contactid == '' ? _id + '' : _id + ',' + item.contactid;
				}
			});
			this.init();
			this.showMsg();
			var self = this;
			var __t = setTimeout(function() {
				clearTimeout(__t);
				__t = null;
				self.setRecentItemNick(par);
				/*
				self.mailRecentListDOM.each(function(item) {
					var __id = item.contact_id ? item.contact_id : item.getAttribute('contact_id');
					if(__id == par.id) {
						item.firstChild.firstChild.nextSibling.firstChild.firstChild.innerHTML = par.nickname;
					}
				});
				*/
			}, 200);
		} else {
			_dialog.alert({info: ret.msg});
		}
	},
	
	createCfailureCallback: function() {
		_dialog.alert({info: '由于网络原因，创建失败，请重试！'});
	},
	
	editC: function() {
		
	},
	
	// 创建联系人信息的时候，判断联系人信息的合法性，返回一个数组
	checkContactPars : function() {
		var name = toTrimDBC($('ncName').value.strip()).toLowerCase();
		var nick = toTrimDBC($('ncNick').value.strip()).toLowerCase();
		var fmail = toTrimDBC($('ncFmail').value.strip()).toLowerCase();
		var bmail = toTrimDBC($('ncBmail').value.strip()).toLowerCase();
		var mobile = toTrimDBC($('ncMobile').value.strip()).toLowerCase();
		var hp = toTrimDBC($('ncHP').value.strip()).toLowerCase();
		var op = toTrimDBC($('ncOP').value.strip()).toLowerCase();
		var f = toTrimDBC($('ncF').value.strip()).toLowerCase();
		var pager = toTrimDBC($('ncPager').value.strip()).toLowerCase();
		var h = toTrimDBC($('ncH').value.strip()).toLowerCase();
		var hpost = toTrimDBC($('ncHPost').value.strip()).toLowerCase();
		var o = toTrimDBC($('ncO').value.strip()).toLowerCase();
		var opost = toTrimDBC($('ncOPost').value.strip()).toLowerCase();
		var year = toTrimDBC($('ncYear').value.strip()).toLowerCase();
		var month = toTrimDBC($('ncMonth').value.strip()).toLowerCase();
		var day = toTrimDBC($('ncDay').value.strip()).toLowerCase();
		var note = toTrimDBC($('ncNote').value.strip()).toLowerCase();
		var page = toTrimDBC($('ncPage').value.strip()).toLowerCase();
		
		if (!checkSpecial(nick, '昵称中不能包含特殊字符')) {
			return [];
		}
		
		if(nick == '') {
			_dialog.alert({info: '联系人昵称不能为空！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return [];
		}
		
		if(this._check_length(nick) > 20) {
			_dialog.alert({info: '联系人昵称太长！请限制在10个汉字或20个英文字母以内！', click: function() {
				if(mailAddressClass.current_focus_el) {
					mailAddressClass.current_focus_el.focus();
				}
			}});
			return [];
		}
		
		if (!IsEmail(fmail)) {
			return [];
		}
		
		// 判断生日填写的格式是否正确
		if (year != '') {
			if (!(!isNaN(year) && year > 1920 && year < 2008)) {
				_dialog.alert({info: '生日格式填写不正确，请重新填写'});
				return [];
			}
		}
		if (month != '') {
			if (!(!isNaN(month) && month > 0 && month < 13)) {
				_dialog.alert({info: '生日格式填写不正确，请重新填写'});
				return [];
			}
		}
		if (day != '') {
			if (!(!isNaN(day) && day > 0 && day < 32)) {
				_dialog.alert({info: '生日格式填写不正确，请重新填'});
				return [];
			}
		}
		if (mobile != '') {
			if (isNaN(mobile)) {
				_dialog.alert({info: '手机号码格式不正确'});
				return [];
			}
		}
		if (hpost != '') {
			if (isNaN(hpost)) {
				_dialog.alert({info: '邮政编码格式不正确'});
				return [];
			}
		}
		if (opost != '') {
			if (isNaN(opost)) {
				_dialog.alert({info: '邮政编码格式不正确'});
				return [];
			}
		}
		var groupName = this.getSelectedGroupName();
		var postbirth = this.getBirth(year, month, day);
		return [name, nick, fmail, bmail, groupName, mobile, hp, op, f, h, hpost,
				o, opost, postbirth, note, page];
	},

	getBirth : function(y, m, d) {
		y = y.strip();
		m = m.strip();
		d = d.strip();
		if (y == "" && m != "" && d != "") {
			return "0000-" + m + "-" + d;
		} else if (y != "" && m == "" && d != "") {
			return y + "-00-" + d;
		} else if (y != "" && m != "" && d == "") {
			return y + "-" + m + "-00";
		} else if (y == "" && m == "" && d != "") {
			return "0000-00" + d;
		} else if (y == "" && m != "" && d == "") {
			return "0000-" + m + "-00";
		} else if (y != "" && m == "" && d == "") {
			return y + "-00-00";
		} else if (y == "" && m == "" && d == "") {
			return "0000-00-00";
		} else {
			return y + "-" + m + "-" + d;
		}
	},

	// 获得选中的组列表
	getSelectedGroupName : function() {
		var hsArray = [];
		var hs = '';
		contactCates.each(function(item) {
			if(item.id <= 0) return;
			var _it = $('ncGroup' + item.id);
			if (_it.checked) {
				hsArray.push(_it.value);
			}
		});
		return hsArray.join(',');
	},
	
	// 显示操作成功的提示信息
	showMsg: function() {
	/*
		var _msg_div = $('messageDiv');
		var t = setTimeout(function() {
			try {
				Element.show(_msg_div);
			} catch(e) {}
			clearTimeout(t);
			t = null;
		}, 200);
		var _t = setTimeout(function() {
			try {
				if(_msg_div) Element.hide(_msg_div);
			} catch(e) {}
			clearTimeout(_t);
			_t = null;
		}, 3000);
		*/
		Tips.show('操作成功', 5);
	},
	
	// 导出联系人
	exportAddress: function() {
	},
	
	importAddress : function() {
		this.importSendMail = [];
		this.clearList(this.AddrList);
		this.clearDragEvent();
		this.clearGroupDragEvent();
		DOM.addressGroupList.innerHTML = addr_import;
		mailUploadFile.createIframe();
	},
	
	importOtherAddress : function(el) {
		var name = $('import_other_email').value;
		var pwd = $('import_other_pwd').value;
		if(name.blank() || pwd.blank()) {
			_dialog.alert({info: '用户名密码不能为空！'});
			return;
		}
		var site = "";
		switch($('import_other_select').selectedIndex) {
			case 0:
				site = "163";
				break;
			/*
			case 1:
				site = "126";
				break;
			*/
			case 1:
				site = "tom";
				break;
			case 2:
				site = "sina";
				break;
			case 3:
				site = "yahoo";
				break;
			default:
				break;
		}
		var _replace = $('import_other_rep1').checked ? 0 : 1;
		var params = {
			name: name,
			passwd: pwd,
			servername: site,
			replace: _replace
		};
		import_other_addr(params, this.importAddrCallback.bind(this), this.importOtherAddressFailureCallBack.bind(this, el));
		this._import_button = el;
		el.setAttribute('disabled', 'true');
		el.value = '导入中...';
	},
	
	importOtherAddressCallBack : function(el, ret) {
		try {
			el.removeAttribute('disabled');
			el.value = '确　定';
		} catch(e) {}
		if(ret.status == true) {
			$('address_import_succ').show();
			$('import_other_email').value = "";
			$('import_other_pwd').value = "";
		} else {
			_dialog.alert({info: ret.errmsg});
		}
	},
	
	importOtherAddressFailureCallBack: function(el) {
		try {
			el.removeAttribute('disabled');
			el.value = '确　定';
		} catch(e) {}
		_dialog.alert({info: '导入失败，请重新导入'});
	},
	
	// 搜索联系人
	searchContact: function(str) {
		var _DOM = this.currentGroupId == -1 ? this.mailRecentListDOM : this.mailAddrListDOM;
		if(str.blank()) {
			_DOM.each(function(item) {
				Element.show(item);
			});
			Element.hide($('searchInfo'));
			return;
		}
		
		_DOM.each(function(item) {
			var s = item.firstChild.getElementsByTagName('div')[1].firstChild.firstChild;
			var s1 = s.innerHTML;
			var s2 = item.firstChild.lastChild.innerHTML;
			var s3 = s.pinyin ? s.pinyin : s.getAttribute('pinyin');
			var s3_flag = false;
			if(s3.strip() != '') {
				s3 = s3.split(' ');
				s3.each(function(item) {
					if(item.toLowerCase().strip().startsWith(str)) {
						s3_flag = true;
					}
				});
			}
			if(s1.toLowerCase().strip().startsWith(str) || s2.toLowerCase().strip().startsWith(str) || s3_flag) {
				Element.show(item);
			} else {
				Element.hide(item);
			}
		});
		var _si = $('searchInfo');
		if(!Element.visible(_si)) {
			Element.show(_si);
			_si.firstChild.innerHTML = '在当前组中查找到符合条件的联系人信息如下：';
		}
		if (this.currentGroupId != 0) {
			var _op = $('mail_contact_list').getElementsByTagName('span')[0];
			if (Element.visible(_op)) {
				Element.hide(_op)
			}
		}
	},
	
	searchBlur: function(el) {
		if(el.value == '') return;
		el.value = '';
		// this.searchContact('');
	},
	
	// 地址簿的导入
	importAddr: function() {
		var el = $('import_address');
		if(el.value.blank()) {
			_dialog.alert({info: '请选择需要导入的地址簿'});
			return;
		}
		if(!el.value.toLowerCase().endsWith('.csv')) {
			_dialog.alert({info: '请选择格式为.csv 的文件导入！'});
			return;
		}
		el.parentNode.parentNode.submit();
		var _au = $('address_upload');
		var _aui = $('address_upload_info');
		_au.hide();
		_aui.show();
		_aui.firstChild.innerHTML = el.value;
	},
	
	// 导入成功
	importAddrCallback: function(ret) {
		if(typeof ret == 'string') ret = ret.evalJSON();
		if(ret.status == true) {
			var self = this;
			var html = [];
			var data = {};
			var _list = $A(ret.msg);
			_list.each(function(item) {
				html.push('<tr><td>'+ item.nickname +'</td><td>'+ item.email +'</td></tr>');
				self.importSendMail.push(item.email);
			});
			
			data['import_email'] = '';
			data['current_name'] = SUID;
			data['current_email'] = UserSohuID;
			data['import_list'] = html.join('');
			var _iaa = $('import_address_area');
			try {
				if (_iaa) _iaa.innerHTML = new Template(addr_import_succ).evaluate(data);
			} catch(e) {}
			this.initCache(true);
		} else {
			try {
				if(this._import_button) var el = this._import_button;
				el.removeAttribute('disabled');
				el.value = '确　定';
			} catch(e) {}
			_dialog.alert({info: '导入失败！'});
		}
		try {
			this.cancelImport();
		} catch(e) {}
	},
	
	cancelImport: function() {
		mailUploadFile.createIframe();
		var el = $('import_address');
		if (el) {
			var _form = el.parentNode.parentNode;
			var _au = $('address_upload');
			var _aui = $('address_upload_info');
			_au.show();
			_aui.hide();
			try {
				_form.removeChild(el);
				Element.insert(_form, {
					top: '<input id="import_address" name="import_address" type="file" style="margin:0px 4px 0px 0px;height:22px;padding:0px;" />'
				});
			} 
			catch (e) {
			}
		}
	},
	
	// 导入成功之后，向所有导入成功的联系人发送信件
	sendMail: function() {
		if(!this.importSendMail) return;
		if(this.importSendMail.length == 0) return;
		var ct = $('import_succ_send_content').value;
		var params = {
			subject : $('import_succ_send_subject').value,
			to : this.importSendMail.join(','),
			content : ct,
			text : ct,
			special: 1
		};
		mail_send(params, this.sendMailCallback.bind(this), this.sendMailFailureCallback.bind(this));
	},
	
	sendMailCallback: function(ret) {
		/*
		if(ret.is_success == true) {
			$('import_succ_area').hide();
			$('send_succ_area').show();
		} else {
			_dialog.alert({info: ret.errmsg});
		}
		*/
		$('import_succ_area').hide();
		$('send_succ_area').show();
	},
	
	sendMailFailureCallback: function() {
		_dialog.alert({info: '通知信件发送失败，请重试！'});
	},
	destroy: function() {
		var _event = ['click', 'focus', 'blur', 'mouseover', 'mouseout', 'mousedown', 'mouseup', 'mousemove', 'keydpwn', 'keyup', 'keypress'];
		try {
			this.clearDragEvent();
		} catch(e) {}
		try {
			$A(this.mailAddrListDOM.concat(this.mailRecentListDOM)).each(function(item) {
				$A(item.getElementsByTagName('*')).each(function(_item) {
					_event.each(function(__item) {
						Event.stopObserving(_item, __item);
						if(typeof _item['on' + __item] === 'function') _item['on' + __item] = null;
					});
					_item = null;
				});
			});
		} catch(e) {}
	}
};
var mailAddressClass = new MailAddress();
